package com.ai.chatai.repository;

import jakarta.annotation.PostConstruct;

import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Properties;

@Slf4j
@Component
@RequiredArgsConstructor
public class LocalPdfFileRepository implements FileRepository{
    private final VectorStore vectorStore;

    //会话Id与文件名的对应关系，方便查询会话历史时重新加载文件
    //properties文件自带持久化，所以不用map存储
    private final Properties chatFiles =new Properties();
    @Override
    public boolean save(String chatId, Resource resource) {
        //1.保存到本地磁盘
        String fileName = resource.getFilename();
        File target = new File(Objects.requireNonNull(fileName));
        if(!target.exists()){
            try {
                Files.copy(resource.getInputStream(),target.toPath());
            }catch (IOException e){
                log.error("保存文件失败",e);
                return false;
            }
        }
        //2.保存到映射关系
        chatFiles.put(chatId,fileName);
        return true;
    }

    @Override
    public Resource getFile(String chatId) {
        String fileName = chatFiles.getProperty(chatId);
        return new FileSystemResource(fileName);
    }

    @PostConstruct
    private void init(){
        FileSystemResource pdfResource=new FileSystemResource("chat-pdf.properties");
        if(pdfResource.exists()){
            try {
                chatFiles.load(new BufferedReader(new InputStreamReader(pdfResource.getInputStream())));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }//读取保存的会话id与文件名的映射关系
        FileSystemResource vectorResource=new FileSystemResource("chat-vector.json");
        if(vectorResource.exists()){
            SimpleVectorStore simpleVectorStore = (SimpleVectorStore)vectorStore;
            simpleVectorStore.load(vectorResource);
        }
        //读取保存的向量库
    }
    @PreDestroy
    private void persistent(){
        try {
            chatFiles.store(new FileWriter("chat-pdf.properties"), LocalDateTime.now().toString());
            //持久化保存到
            SimpleVectorStore simpleVectorStore = (SimpleVectorStore)vectorStore;
            simpleVectorStore.save(new File("chat-pdf.json"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}